package gitee.cheungming.modules.governance.controller;

import cn.dev33.satoken.oauth2.config.SaOAuth2ServerConfig;
import cn.dev33.satoken.oauth2.consts.GrantType;
import cn.dev33.satoken.oauth2.data.model.loader.SaClientModel;
import cn.dev33.satoken.oauth2.processor.SaOAuth2ServerProcessor;
import gitee.cheungming.modules.governance.dto.ClientDTO;
import gitee.cheungming.modules.governance.service.ClientService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * Sa-Token OAuth2 Server端 控制器
 */
@RestController
public class SaOAuth2ServerController {

    @Resource
    ClientService clientService;

    @RequestMapping("/oauth2/token")
    public Object clientToken() {
        return SaOAuth2ServerProcessor.instance.clientToken();
    }

    // Sa-Token OAuth2 定制化配置
    @Autowired
    public void configOAuth2Server(SaOAuth2ServerConfig oauth2Server) {
        List<ClientDTO> list = clientService.list(new HashMap<>());
        for (ClientDTO client : list) {
            oauth2Server.addClient(
                    new SaClientModel()
                            .setClientId(client.getClientKey())    // client id
                            .setClientSecret(client.getClientSecret())    // client 秘钥
                            .addAllowRedirectUris("*")    // 所有允许授权的 url
                            .addAllowGrantTypes(     // 所有允许的授权模式
                                    GrantType.refresh_token,  // 刷新令牌
                                    GrantType.client_credentials  // 客户端模式
                            )
            );
        }
    }
}

